#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <stdlib.h>
#include <unistd.h>
int main()
{
    int pipefd[2] = {};
    int ret = pipe(pipefd);
    if(ret < 0){
        perror("pipe");
        return 0;
    }
    // pipefd[0] 读 pipefd[1] 写
    pid_t pid = fork();
    // 子写 父读
    if(pid == 0)
    {
        // 子进程
        close(pipefd[0]);
        char buffer[1024] = {};
        sprintf(buffer, "I am a child process, pid : %d", getpid());
        int n = 8;
        while(n--)
        {
            int n = write(pipefd[1], buffer, sizeof(buffer));
            if(n < 0)
            {
                perror("write");
                break;
            }
            sleep(1);
        }
        exit(0);
    }
    // 父进程
    close(pipefd[1]);
    char buffer[1024] = {};
    while(1)
    {
        int n = read(pipefd[0], buffer, sizeof(buffer) - 1);
        if(n > 0)
        {
            buffer[n] = 0;
            printf("%s\n",buffer);
        }
        else if(n == 0)
        {
            printf("子进程退出\n");
            break;
        }
        else
        {
            perror("read");
            break;
        }
    }
    int status = 0;
    ret = waitpid(pid, &status, 0);
    if(ret == pid)
    {
        if(WIFEXITED(status)) printf("%d\n", WEXITSTATUS(status));
        printf("回收子进程成功\n");
    }
    return 0;
}